from bson import ObjectId
from datetime import datetime
from .. import db

class Field:
    def __init__(self, name, area, current_crop, boundary=None, id=None):
        self.id = id if id is not None else len(db.fields) + 1
        self.name = name
        self.area = area
        self.current_crop = current_crop
        self.boundary = boundary
        self.created_at = datetime.utcnow()
    
    def save(self):
        """保存农田信息"""
        if not hasattr(self, 'id'):
            self.id = len(db.fields) + 1
        db.fields.append(self)
        return self
    
    @staticmethod
    def find_by_id(field_id):
        """通过ID查找农田"""
        for field in db.fields:
            if field.id == int(field_id):
                return field
        return None
    
    def update(self, data):
        """更新农田信息"""
        try:
            self.name = data.get('name', self.name)
            self.area = data.get('area', self.area)
            self.current_crop = data.get('current_crop', self.current_crop)
            if 'boundary' in data:
                self.boundary = data['boundary']
            return True
        except Exception as e:
            print(f"Error updating field: {str(e)}")
            return False
    
    def delete(self):
        """删除农田"""
        try:
            db.fields.remove(self)
            return True
        except Exception as e:
            print(f"Error deleting field: {str(e)}")
            return False
    
    def to_dict(self):
        """转换为字典"""
        # 确保边界数据存在且格式正确
    
        return {
            'id': self.id,
            'name': self.name,
            'area': self.area,
            'current_crop': self.current_crop,
            'boundary': self.boundary,
            'created_at': self.created_at.isoformat()
        }


class PlantingRecord:
    def __init__(self, field_id, crop_name, variety=None, plant_date=None, 
                 harvest_date=None, status=None, _id=None):
        self.field_id = field_id
        self.crop_name = crop_name
        self.variety = variety
        self.plant_date = plant_date
        self.harvest_date = harvest_date
        self.status = status
        self._id = _id

    def save(self):
        record_data = {
            'field_id': self.field_id,
            'crop_name': self.crop_name,
            'variety': self.variety,
            'plant_date': self.plant_date,
            'harvest_date': self.harvest_date,
            'status': self.status
        }
        
        if not self._id:
            result = db.planting_records.insert_one(record_data)
            self._id = result.inserted_id
        else:
            db.planting_records.update_one(
                {'_id': self._id},
                {'$set': record_data}
            )
        return self

    @staticmethod
    def find_by_field(field_id):
        return [
            PlantingRecord(
                field_id=r['field_id'],
                crop_name=r['crop_name'],
                variety=r.get('variety'),
                plant_date=r.get('plant_date'),
                harvest_date=r.get('harvest_date'),
                status=r.get('status'),
                _id=r['_id']
            )
            for r in db.planting_records.find({'field_id': field_id})
        ]

    def to_dict(self):
        return {
            'id': str(self._id),
            'field_id': str(self.field_id),
            'crop_name': self.crop_name,
            'variety': self.variety,
            'plant_date': self.plant_date.isoformat() if self.plant_date else None,
            'harvest_date': self.harvest_date.isoformat() if self.harvest_date else None,
            'status': self.status
        } 